package bean.managed;

import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.RightEntityFacade;
import bean.session.SystemUserEntityFacade;


import entity.RightEntity;
import entity.RoleEntity;
import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.DualListModel;
import org.primefaces.model.TreeNode;
import session.stateful.RightBean;

@ManagedBean(name = "ARController")
@SessionScoped
public class ARController extends AbstractBacking implements Serializable {

    List<String> allRights = new ArrayList<String>();
    List<String> userRights = new ArrayList<String>();
    //Collection<RightEntity> userRights = getList();
//    private DualListModel<RightEntity> rightsPickList;
//    private DualListModel<RightEntity> rightsPickedList;
    private DualListModel<String> rightsPickList;
    private List<RightEntity> allRightsEntityList;
    private List<RightEntity> userRightsEntityList;
    private TreeNode root;
    private List<RightEntity> rightList;
    private List<RoleEntity> roleList;
    private List<String> AvailableRightListOfRoles;

    public List<String> getAvailableRightListOfRoles() {
         AvailableRightListOfRoles =new ArrayList<String>();
         roleList = new ArrayList<RoleEntity>(selectedUser.getRoles());
         for (int i = 0; i < roleList.size(); i++) {
             rightList = new ArrayList<RightEntity>(roleList.get(i).getRights());
              for (int j = 0; j < rightList.size(); j++) {
               String rightString = rightList.get(j).getRightName();
              
                AvailableRightListOfRoles.add(rightString);
              }
         }
    
        return AvailableRightListOfRoles;
    }

    public void setAvailableRightListOfRoles(List<String> AvailableRightListOfRoles) {
        this.AvailableRightListOfRoles = AvailableRightListOfRoles;
    }

  
    public TreeNode getRoot() {
        roleList = new ArrayList<RoleEntity>(selectedUser.getRoles());
        root = new DefaultTreeNode("root", null);
        TreeNode roleHeader = new DefaultTreeNode("Roles", root);
        AvailableRightListOfRoles =new ArrayList<String>();
        for (int i = 0; i < roleList.size(); i++) {
            TreeNode role = new DefaultTreeNode("  " + roleList.get(i).getRoleName(), roleHeader);
            TreeNode rightHeader = new DefaultTreeNode("Access Rights", role);

            rightList = new ArrayList<RightEntity>(roleList.get(i).getRights());
          
            for (int j = 0; j < rightList.size(); j++) {
                String rightString = "  " + rightList.get(j).getRightName();
              
                
                TreeNode right = new DefaultTreeNode(rightString, rightHeader);
            }
        }
          

       
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public void populateTreeTable() {

        root = new DefaultTreeNode("root", null);

        for (int i = 0; i < 3; i++) {
            TreeNode role = new DefaultTreeNode("hihi", root);
        }

    }
    public boolean checkAvailableRights(String r) {
        for (String s : getAvailableRightListOfRoles()) {

            if (r.equalsIgnoreCase(s)) {
                System.out.println(r+"wwwwww");
                return true;
            }
        }
        return false;
    }
    public DualListModel<String> getRightsPickList() {
        if (rightsPickList == null) {
            allRightsEntityList = new ArrayList<RightEntity>();

            userRightsEntityList = new ArrayList<RightEntity>(getList());
            allRightsEntityList = ejbFacade.findAllIncludeArchived();
            
            for (int i = 0; i < allRightsEntityList.size(); i++) {
                if (!(userRightsEntityList.contains(allRightsEntityList.get(i)))&&!(checkAvailableRights(allRightsEntityList.get(i).getRightName()))){
                    allRights.add(allRightsEntityList.get(i).getRightName());
                }
            }
         
            for (int i = 0; i < userRightsEntityList.size(); i++) {
                userRights.add(userRightsEntityList.get(i).getRightName());
            }

            rightsPickList = new DualListModel<String>(allRights, userRights);
            return rightsPickList;
        }
        return rightsPickList;
    }

    public void updateUserRights() {
//        System.out.println("I am here");
//        selectedUser.getRights().add(rightsPickList.getTarget().get(2));
//        getFacade().edit(selectedUser);
        //selectedUser.getRights();
        for (int i = 0; i < rightsPickList.getTarget().size(); i++) {
            //for (int j = 0; j < getList().size(); i++){
            if (getEjbFacade().findRight(rightsPickList.getTarget().get(i)) != null) {
                if (!getList().contains(getEjbFacade().findRight(rightsPickList.getTarget().get(i)))) {
                    getList().add(getEjbFacade().findRight(rightsPickList.getTarget().get(i)));
                }
            }
            // }
        }
        List<RightEntity> allRightsInPickList = new ArrayList();
        for (int i = 0; i < rightsPickList.getTarget().size(); i++) {
            allRightsInPickList.add(getEjbFacade().findRight(rightsPickList.getTarget().get(i)));
        }

        Iterator itr = getList().iterator();
        while (itr.hasNext()) {

            if (!allRightsInPickList.contains(itr.next())) {
                itr.remove();
            }
        }
      
        selectedUser.setRights(getList());
        selectedUser.modified(getLoginPerson());
        getFacade().edit(selectedUser);
        rightsPickList = null;
        allRights.clear();
        userRights.clear();
    }

    public void setRightsPickList(DualListModel<String> rightsPickList) {
        this.rightsPickList = rightsPickList;
    }
    //private rightsPickList = new DualListModel<RightEntity>(allRights, userRights);
    //private RightEntity right;
    private RightEntity selectedRight;

    public RightEntity getSelectedRight() {
        return selectedRight;
    }

    public void setSelectedRight(RightEntity selectedRight) {
        this.selectedRight = selectedRight;
    }
    @ManagedProperty(value = "#{list}")
    private Collection<RightEntity> list;

    public Collection<RightEntity> getList() {
        return selectedUser.getRights();
    }

    public void setList(Collection<RightEntity> list) {
        this.list = list;
    }
    private String status;
    public SystemUserEntity curr;
    private SystemUserEntity selectedUser;
    private String[] sel;
    private session.stateful.RightBean bean;

    public String[] getSel() {
        return sel;
    }

    public void setSel(String[] sel) {
        this.sel = sel;
    }
    private String result;
    private List<SystemUserEntity> user;
    private Map<String, String> ARs;

    public void setARs(Map<String, String> ARs) {
        this.ARs = ARs;
    }
    @EJB
    private bean.session.RightEntityFacade ejbFacade;

    public RightEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(RightEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public Map<String, String> getARs() {

        List<RightEntity> list1 = new ArrayList<RightEntity>();
        list1 = ejbFacade.findAllIncludeArchived();
        ARs = new HashMap<String, String>();
        String[] k = new String[list1.size()];

        for (int i = 0; i < list1.size(); i++) {
            RightEntity r = list1.get(i);
            k[i] = r.getRightName();
            ARs.put(k[i], k[i]);
        }
        return ARs;
    }
    @EJB
    private bean.session.SystemUserEntityFacade facade;

    public ARController() {
    }

    public SystemUserEntity getSelected() {

        if (curr == null) {
            curr = new SystemUserEntity();
        }
        return curr;
    }
    private List<RightEntity> selectedARs;

    public List<RightEntity> getSelectedARs() {
        //ARs = new ArrayList<RightEntity>();
        return selectedARs;
    }

    public void setSelectedARs(List<RightEntity> selectedARs) {
        selectedARs = new ArrayList<RightEntity>();

        this.selectedARs = selectedARs;
    }

    public String update1() {
        try {
            // for(RoleEntity r:getRoles() ){System.out.println(r.getRoleName()+"hhhhhhh");}
            curr.setRights(getList());
            getFacade().edit(curr);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RolesUpdated"));
            return "ViewRole?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String remove() {
        try {

            Collection<RightEntity> result = getList();
            Collection<RightEntity> result1 = new ArrayList<RightEntity>();
            System.out.println("User Selected1111111111: " + curr);
            for (RightEntity r : getList()) {
                System.out.println(r.getRightName() + "hhhhhhh ");
            }
            String[] lk = getSel();

            System.out.println(lk.length + "aaaaa");
            for (RightEntity r : result) {
                boolean have = false;

                for (int i = 0; i < lk.length; i++) {
                    //check the list for existing rights

                    System.out.println("bbbbbb1" + r.getRightName());
                    System.out.println("cccccccc1" + lk[i]);
                    if ((r.getRightName().equalsIgnoreCase(lk[i]))) {


                        have = true;
                        break;

                    }
                }
                if (!have) {
                    result1.add(r);
                }

            }
            for (RightEntity r1 : result1) {
                System.out.println(r1.getRightName() + "mmmmmmm ");
            }

            setList(result1);
            curr.setRights(result1);

            getFacade().edit(curr);

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccessRightRemoved"));
            return "UserRight?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String update() {
        try {
            Collection<RightEntity> result = getList();

            String[] lk = getSel();
            for (int i = 0; i < lk.length; i++) {
                boolean same = false;

                for (RightEntity r : result) {
                    // System.out.println(lk[i]+"hhhhh"+r.getRightName());
                    if (r.getRightName().equalsIgnoreCase(lk[i])) {
                        same = true;
                        break;
                    }

                }
                if (!same) {
                    System.out.println("lllll1 " + lk[i]);
                    RightEntity r1 = getEjbFacade().findRight(lk[i]);
                    System.out.println("lllll");
                    curr.getRights().add(r1);
                }
            }


//            curr.setRights(result);
            //  for(RightEntity r:getAccessRight() ){System.out.println(r.getRightName()+"hhhhhhh");}

            getFacade().edit(curr);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AcceesRightUpdated"));
            return "UserRight?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String userSelect(SelectEvent event) {
        System.out.println("User Selected: " + selectedUser);
        System.out.println("" + (null == (SystemUserEntity) event.getObject()));
        curr = selectedUser;
        list = curr.getRights();
        setList(selectedUser.getRights());
        for (RightEntity r : list) {
            System.out.println(r.getRightName() + "vvvvvvvvv");
        }
        userRights.clear();
        allRights.clear();
        rightsPickList = null;
        return "UserRight?faces-redirect=true";
    }

    public String rightSelect(SelectEvent event) {
        System.out.println("User Selected: " + selectedRight);
        System.out.println("" + (null == (RightEntity) event.getObject()));
        curr = selectedUser;


        for (RightEntity r : list) {
            System.out.println(r.getRightName() + "vvvvvvvvv");
        }
        return "UserRight?faces-redirect=true";
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void statusUpdate(String status) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(status, null));
    }

    public void discard() {
        //reset current
        curr = new SystemUserEntity();
        selectedUser = curr;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public List<SystemUserEntity> getUser() {
        user = new ArrayList<SystemUserEntity>();
        user = facade.findAllIncludeArchived();

        return user;
    }

    public void setUsers(ArrayList<SystemUserEntity> msg) {
        this.user = msg;
    }

    public SystemUserEntity getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(SystemUserEntity selectedUser) {
        this.selectedUser = selectedUser;
    }

    public SystemUserEntity getCurrent() {
        return curr;
    }

    public void setCurrent(SystemUserEntity current) {
        this.curr = current;
    }

    public SystemUserEntityFacade getFacade() {
        return facade;
    }

    public void setFacade(SystemUserEntityFacade userBean) {
        this.facade = userBean;
    }

}
